package com.zcup.miaosha.controller;

import com.zcup.miaosha.service.CommodityService;
import com.zcup.miaosha.service.UserService;
import com.zcup.miaosha.utils.ratelimiter.ExtRateLimiter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(description = "商品处理")
@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private UserService userService;

    @ExtRateLimiter(permitsPerSeconds = 100.0,timeouts = 500)
    @ApiOperation("秒杀测试接口")
    @GetMapping("kill/{id}")
    public String kill(@PathVariable int id){
        int orderId = 0;
        try{
            orderId = commodityService.kill(id);
        }catch (RuntimeException e){
            System.out.println(e.getMessage());
        }
        return orderId == 0 ? "秒杀失败" : "秒杀成功";
    }


    @ExtRateLimiter(permitsPerSeconds = 100.0, timeouts = 1000)
    @ApiOperation("秒杀商品")
    @GetMapping("kill/{id}/{userId}/{md5}")
    public String kill(@PathVariable("id") int id,
                       @PathVariable("userId") int userId,
                       @PathVariable("md5") String md5){
        int orderId = 0;

        try{
            //验证用户调用接口频率
            userService.saveUserCount(userId);
            if (userService.getUserCount(userId)) {
                throw new RuntimeException(userId + "用户调用接口频率过高,秒杀动作已取消");
            }
            orderId = commodityService.kill(id,userId,md5);
        }catch (RuntimeException e){
            System.out.println(e.getMessage());
        }
        //悲观锁需要加在这,因为事务自带锁
        // int orderId = 0;
        // try {
        //     synchronized (this){
        //         orderId = commodityService.kill(id);
        //     }
        // }catch (Exception e){
        //     // e.printStackTrace();
        //     return e.getMessage();
        // }
        return orderId == 0 ? "秒杀失败" : "秒杀成功";
    }

    @GetMapping("md5")
    public String getMd5(@RequestParam("id") Integer id, @RequestParam("userId") Integer userId){
        String md5;
        try{
            md5 = commodityService.getMd5(id,userId);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return "获取md5失败";
        }
        return "获取到的MD5为:" + md5;
    }
}
